﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Reflection;

namespace Dummy.Web
{
    public class GameServer
    {
        Thread _serverThread;
        bool _isServerRun = false;
        ManualResetEvent _TcpClientConnected = new ManualResetEvent(false);
        TcpListener _Listener = new TcpListener(IPAddress.Any, 4530); //Allowed port range 4502-4532
        List<GameClient> _gameClients = new List<GameClient>();
        object _gameService;
        
        public GameServer(object service)
        {
            _gameService = service;            
        }

        public void StartServer()
        {
            if (_isServerRun)
                StopServer();
            _serverThread = new Thread(ServerProcess);
            _serverThread.Start();
        }

        private void ServerProcess()
        {
            try
            {                
                _Listener.Start();
                _isServerRun = true;
                while (_isServerRun)
                {
                    _TcpClientConnected.Reset();
                    _Listener.BeginAcceptTcpClient(new AsyncCallback(OnBeginAccept), _gameService);
                    _TcpClientConnected.WaitOne(); //Block until client connects
                }
            }
            catch (Exception ex)
            {
                //LogError(exp);
                StopServer();
            }
        }

        public void StopServer()
        {
            _isServerRun = false;
            foreach (GameClient client in _gameClients)
                client.StopClient();
            _Listener.Stop();            
        }

        private void OnBeginAccept(IAsyncResult ar)
        {
            _TcpClientConnected.Set(); //Allow waiting thread to proceed
            TcpListener listener = _Listener;
            TcpClient client = listener.EndAcceptTcpClient(ar);
            if (client.Connected)
            {
                GameClient newgameclient = new GameClient(client, _gameService);

                //client.Client.BeginReceive(
                //client.Client.Receive(
                /*
                StreamWriter writer = new StreamWriter(client.GetStream());
                writer.AutoFlush = true;
                writer.WriteLine(getData());
                */
            }
        }
    }    
}